package com.googlecode.layout4j.parser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.googlecode.layout4j.domain.SimpleContentRef;
import com.googlecode.layout4j.domain.SimpleContentRefImpl;

/**
 * Helper for ContentExtractor - a SAX handler for extracting content references from layoutML.
 * 
 * <p>Ignores content inside any column with <code>aside="true"</code>.
 * 
 * @author Matt Humphreys
 * @see ContentExtractor
 */
public class ContextExtractorHandler extends DefaultHandler {
	public static final String EL_CONTENT 	= ConstantsUtil.dontInline("content");
	public static final String EL_COLUMN 	= ConstantsUtil.dontInline("column");	// For aside attr
	public static final String ATTR_ID 		= ConstantsUtil.dontInline("data-id");
	public static final String ATTR_TYPE 	= ConstantsUtil.dontInline("data-type");
	public static final String ATTR_STYLE 	= ConstantsUtil.dontInline("style");
	public static final String ATTR_ASIDE 	= ConstantsUtil.dontInline("aside");
	public static final String VALUE_ASIDE_TRUE		= ConstantsUtil.dontInline("true");

	private List<SimpleContentRef> contentList = new ArrayList<SimpleContentRef>();
	private boolean isAside = false;

	public List<SimpleContentRef> getContentList() {
		return contentList;
	}
	
	@Override
	public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) 
			throws SAXException {
		if (qName.equals(EL_CONTENT)) {
			SimpleContentRef content = toContentRef(attrs);
			if ((content != null) && (!isAside)) {
				contentList.add(content);
			}
		} else {
			if (qName.equals(EL_COLUMN)) {
				if (isAside(attrs)) {
					isAside = true;
				}
			}
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (qName.equals(EL_COLUMN)) {
			isAside = false;
		}
	}
	
	private boolean isAside(Attributes attrs) {
		return (VALUE_ASIDE_TRUE.equals(attrs.getValue(ATTR_ASIDE)));
	}
	
	public static SimpleContentRef toContentRef(Attributes attrs) {
		String id = attrs.getValue(ATTR_ID); 		// Assume attribute exists
		String type = attrs.getValue(ATTR_TYPE); 	// Assume attribute exists
		String style = attrs.getValue(ATTR_STYLE); 	// Assume attribute exists
		SimpleContentRefImpl content = new SimpleContentRefImpl();
		content.setDataId(id);
		content.setDataTypeId(type);
		content.setStyleId(style);
		return content;
	}
}
